package com.iiapk.gridview.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class GridDataBase {
	
	private static final String DB_NAME = "grid.db";
	private static final int DB_VERSION = 1;
	private Context mContext = null;
	private boolean isDatabaseOprating;

	private SQLiteDatabase sqLiteDatabase = null;
	private SqliteHelper sqliteHelper = null;

	private static class SqliteHelper extends SQLiteOpenHelper {
		public SqliteHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(GridItem.CREATE_DATABASE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + GridItem.TABLE);
			onCreate(db);
		}
	}

	public GridDataBase(Context context) {
		mContext = context;
	}

	public boolean open() {
		if (isDatabaseOprating) {
			return false;
		}
		sqliteHelper = new SqliteHelper(mContext);
		sqLiteDatabase = sqliteHelper.getWritableDatabase();
		isDatabaseOprating = true;
		return true;
	}

	public void close() {
		sqliteHelper.close();
		isDatabaseOprating = false;
	}

	public void insertItems(List<GridItem> items) {
		sqLiteDatabase.beginTransaction();
		sqLiteDatabase.setTransactionSuccessful();
		int sum = items.size();
		for (int i = 0; i < sum; i++) {
			GridItem item = items.get(i);
			ContentValues ivalues = new ContentValues();
			//ivalues.put(GridItem.ID, item.id);
			ivalues.put(GridItem.ICON, item.icon);
			ivalues.put(GridItem.TEXT, item.text);
			sqLiteDatabase.insert(GridItem.TABLE, null, ivalues);
		}
		sqLiteDatabase.endTransaction();
	}

	public List<GridItem> getItems() {
		ArrayList<GridItem> items = new ArrayList<GridItem>();
		Cursor cursor = sqLiteDatabase.query(GridItem.TABLE, null, null,null, null, null, null);
		cursor.moveToFirst();
		do {
			GridItem item = new GridItem();
			item.id=cursor.getInt(0);
			item.text=cursor.getString(1);
			item.icon=cursor.getInt(2);
			items.add(item);
		} while (cursor.moveToNext());
		cursor.close();
		return items;
	}

	public boolean hasItems() {
		Cursor cursor = sqLiteDatabase.query(GridItem.TABLE, null, null, null, null, null, null);
		Boolean is = cursor.moveToFirst();
		cursor.close();
		return is;
	}

	public Boolean deleteItems() {
		return sqLiteDatabase.delete(GridItem.TABLE, null, null) > 0;
	}

}
